package net.huashitong.node.service;

import com.sirdc.modules.core.dao.BaseDao;
import com.sirdc.modules.sys.base.StringPKService;
import com.sirdc.modules.sys.filter.NodeNewschedulesModel;
import com.sirdc.modules.sys.service.SysTableService;
import com.sirdc.modules.utils.NumberUtils;
import com.sirdc.modules.utils.ObjectUtils;
import com.sirdc.modules.utils.StringUtils;
import net.huashitong.Project.entity.NewProjects;
import net.huashitong.Project.service.NewProjectsService;
import net.huashitong.node.dao.NodeNewschedulesDao;
import net.huashitong.node.entity.NodeNewschedules;
import net.huashitong.node.filter.NodeNewschedulesFilter;
import net.huashitong.user.entity.BnpUser;
import net.huashitong.user.filter.BnpUserFilter;
import net.huashitong.user.filter.OnlineFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigInteger;
import java.util.*;

@Service
public class NodeNewschedulesService extends StringPKService<NodeNewschedules> {
    @Autowired
    private NodeNewschedulesDao dao;
    @Autowired
    private SysTableService tableService;
    @Autowired
    private NewProjectsService newProjectsService;

    @Override
    protected BaseDao<NodeNewschedules, String> getDao() {
        return dao;
    }

    @Override
    protected void beforeSave(NodeNewschedules obj) {
        obj.setSysId(tableService.updateMaxSysId("t_bnp_node_newschedule", null));
    }

    public List<NodeNewschedules> queryListByNameAndPhone(BnpUserFilter filter) {
        return dao.queryListByNameAndPhone(filter);
    }

    /**
     * 根据经办人名字手机号查询节点清单
     *
     * @param phone
     * @param name
     * @return
     */

    public List<NodeNewschedules> queryByOperator(String phone, String name) {
        return dao.queryOperator(phone, name);
    }

    /**
     * 根据责任人名字手机号查询节点清单
     *
     * @param phone
     * @param name
     * @return
     */
    public List<NodeNewschedules> queryByResUser(String phone, String name) {
        return dao.queryResUser(phone, name);
    }

    public List<NodeNewschedules> queryListByProjectId(String projectId, String type, String resDept, String state, String operatorUser) {

        return dao.queryListByProjectId(projectId, type, resDept, state, operatorUser);
    }

    public NodeNewschedules getNodeNewschedulesByProjectIdAndNodeId(String projectId, String nodeId) {
        return dao.getNodeNewschedulesByProjectIdAndNodeId(projectId, nodeId);
    }

    public List<NodeNewschedules> getNodeNewschedulesByProjectId(String projectId, String nodeId) {
        return dao.getNodeNewschedulesByProjectId(projectId, nodeId);
    }

    public List<String> getProjectId(BnpUserFilter bnpUserFilter) {
        return dao.getProjectIdByResUserAndDept(bnpUserFilter);
    }

    /**
     * 根据一个项目id来返回对应的节点信息
     *
     * @param projectId
     * @return
     */
    public List<NodeNewschedules> getNodeByProjectId(String projectId) {
        return dao.getNodeByProjectId(projectId);
    }

    public List<NodeNewschedules> getNodeByProjectIdAndState(String projectId, String state) {
        return dao.getNodeByProjectIdAndState(projectId, state);
    }

    public List<NodeNewschedules> getNodeByProjectIdAndStatus(String projectId, String status) {
        return dao.getNodeByProjectIdAndStatus(projectId, status);
    }

    public List<NodeNewschedules> getNodePlanTime(String projectId, String num) {
        return dao.getNodePlanTime(projectId, num);
    }

    public List<NodeNewschedules> getNodeIdsList(String nodeIds, String projectId, String state) {
        return dao.getNodeIdsList(nodeIds, projectId, state);
    }

    public List<NodeNewschedules> getNodeIdsLists(String nodeIds, String projectId) {
        return dao.getNodeIdsLists(nodeIds, projectId);
    }

    public List<NodeNewschedules> getNodeIds(String nodeIds, String projectId) {
        return dao.getNodeIds(nodeIds, projectId);
    }

    /**
     * 获取项目名称和节点信息
     *
     * @param projectId
     * @param bnpUser
     * @return
     */
    public List<NodeNewschedules> getNodeAndProjectName(String projectId, BnpUser bnpUser) {
        return dao.getNodeAndProjectName(projectId, bnpUser);
    }

    /**
     * 根据用户查询所有节点（不区分项目）
     *
     * @param bnpUser
     * @return
     */
    public List<NodeNewschedules> getNodeByUser(BnpUser bnpUser) {
        return dao.getNodeByUser(bnpUser);
    }

    public NodeNewschedules getNodeOne(String sysId) {
        return dao.getNodeOne(sysId);
    }

    /**
     * 查询部门管理的大节点
     *
     * @param projectId
     * @param
     * @return
     */
    public List<NodeNewschedules> getBigNode(String projectId, BnpUserFilter bnpUserFilter) {
        return dao.getBigNode(projectId, bnpUserFilter);
    }

    /**
     * 查询某个项目某个大节点下的所有小节点
     *
     * @param nodeId
     * @param projectId
     * @return
     */
    public List<NodeNewschedules> getNode2(String nodeId, String projectId) {
        return dao.getNode2(nodeId, projectId);
    }

    public List<NodeNewschedules> getNode3(String nodeId, String projectId) {
        return dao.getNode3(nodeId, projectId);
    }

    public List<NodeNewschedules> getByResDeptAndOperatorUser(String projectsId, String resDept, String operatorUser, String state) {
        return dao.getByResDeptAndOperatorUser(projectsId, resDept, operatorUser, state);
    }

    public List<NewProjects> queryProjectByAccraditation(NodeNewschedulesFilter nodeNewschedulesFilter) {
        return dao.queryProjectByAccraditation(nodeNewschedulesFilter);
    }

    public List<NodeNewschedules> getNodelistByNodeId(String nodeIds, String projectId, String nextId) {
        return dao.getNodelistByNodeId(nodeIds, projectId, nextId);
    }

    public NodeNewschedules getNnsByProjectIdAndNodeId(String projectId, String nodeId) {
        return dao.getNnsByProjectIdAndNodeId(projectId, nodeId);
    }

    public List<NodeNewschedules> getListNodeIds(String nodeIds, String projectId) {
        return dao.getListNodeIds(nodeIds, projectId);
    }

    public List<NodeNewschedules> getListByPreNodeId(String projectId, String preNodeId) {
        return dao.getListByPreNodeId(projectId, preNodeId);
    }

    public List<NodeNewschedules> getListByPreNodeId2(String nodeId, String projectId) {
        return dao.getListByPreNodeId2(nodeId, projectId);
    }

    public List<NodeNewschedules> getNodesBeforeCurrentNode(String nodeIds, String projectId, String nodeId) {
        return dao.getNodesBeforeCurrentNode(nodeIds, projectId, nodeId);
    }

    //查询某project 完成的所有小节点
    public List<NodeNewschedules> getNode2FinishByProjectId(String projectId, String status) {
        return dao.getNode2ByProjectIdAndStatus(projectId, status);
    }

    /**
     * 项目节点完成率
     *
     * @param projectId
     * @return
     */
    public String getNodeCompletionRate(String projectId) {
        int total = dao.getNodeCompletionOrNotNum(projectId, null);
        int complete = dao.getNodeCompletionOrNotNum(projectId, "2");
        return NumberUtils.calculateRate(complete, total, 0);
    }

    /**
     * 部门节点完成率
     *
     * @return
     */
    public Map<String, Object> getAllDeptNodeCompletionRate() {
        String[] depts = {"永泰县自然资源和规划局", "永泰县住房和城乡建设局",
                "永泰县发展改革局", "永泰县生态环境局",
                "永泰县水利局", "永泰县林业局",
                "永泰县财政局", "永泰县公安消防大队",
                "永泰县人民防空办公室", "永泰县人力资源和社会保障局"};
        Map<String, Object> map = new LinkedHashMap<>();
        int yezhuTotal = dao.getNodeCompletionOrNotNumByDept(null, null);
        double yezhuComplete = (double) dao.getNodeCompletionOrNotNumByDept(null, "2");
        map.put("业主单位", (yezhuComplete / yezhuTotal) * 100);
        for (String dept : depts) {
            int total = dao.getNodeCompletionOrNotNumByDept(dept, null);
            double complete = (double) dao.getNodeCompletionOrNotNumByDept(dept, "2");
            switch (dept) {
                case "永泰县自然资源和规划局":
                    dept = "国土局";
                    break;
                case "永泰县住房和城乡建设局":
                    dept = "住建局";
                    break;
                case "永泰县发展改革局":
                    dept = "发改局";
                    break;
                case "永泰县生态环境局":
                    dept = "环保局";
                    break;
                case "永泰县水利局":
                    dept = "水利局";
                    break;
                case "永泰县林业局":
                    dept = "林业局";
                    break;
                case "永泰县财政局":
                    dept = "财政局";
                    break;
                case "永泰县公安消防大队":
                    dept = "消防大队";
                    break;
                case "永泰县人民防空办公室":
                    dept = "人防办";
                    break;
                case "永泰县人力资源和社会保障局":
                    dept = "人社局";
                    break;
                case "县重点工作攻坚指挥室":
                    dept = "攻坚办";
                    break;
                case "业主单位":
                    dept = "业主单位";
                    break;
                default:
                    dept = "";
                    break;
            }
            if (total != 0) {
                map.put(dept, (complete / total) * 100);
            } else {
                map.put(dept, 0);
            }
        }
        return map;
    }


    public List<NodeNewschedules> getNodeInfo(String projectId, //项目Id(非必填)
                                              String type,      //任务状态      0未开始 1已开始 2结束
                                              String status,    //节点类型      1大节点 2小节点
                                              String state      //节点确定状态   0未确定 1已确定 2不需要
    ) {
        return dao.getNodeInfo(projectId, type, status, state);
    }

    public NodeNewschedules getBigNodesState(String projectId, String nodeId) {
        return dao.getBigNodesState(projectId, nodeId);
    }


    public int getNodeCompletionOrNotNum(String projectId, String status) {
        return dao.getNodeCompletionOrNotNum(projectId, status);
    }

    public List<NodeNewschedules> getNeedBigNodeByProjectId(String projectId) {
        return dao.getNeedBigNodeByProjectId(projectId);
    }

    public List<NodeNewschedules> getNeedSmallNodeByProjectId(String projectId) {
        return dao.getNeedSmallNodeByProjectId(projectId);
    }

    public List<NodeNewschedules> getAllDeptByProId() {
        return dao.getAllDeptByProId();
    }

    public List<NodeNewschedules> getListByType() {
        return dao.getListByType();
    }

    public List<NodeNewschedules> getNoFinishNode(String projectId) {
        return dao.getNoFinishNode(projectId);
    }

    public List<NodeNewschedules> getNodeState() {
        return dao.getNodeState();
    }

    public List<NodeNewschedules> getNodeStateAndStatusByProjectId(String projectId) {
        return dao.getNodeStateAndStatusByProjectId(projectId);
    }

    public List<NodeNewschedules> queryListByFilterZong(NodeNewschedulesFilter filter) {
        return dao.queryListByFilterZong(filter);
    }

    public List<NodeNewschedules> queryListByFilterList(NodeNewschedulesFilter filter) {
        return dao.queryListByFilterList(filter);
    }

    /**
     * 获得审核列表
     *
     * @param filter
     * @return
     */
    public List<Map<String, Object>> getExamineList(NodeNewschedulesFilter filter) {
        List<Map<String, Object>> resList = new ArrayList<>();
        List<NodeNewschedules> allFinishedSmallNodes = dao.queryFinishedSmallNodesByOperatorPhone(filter);          //已完成
        List<NodeNewschedules> allDoingSmallNodes = dao.queryListByFilterList(filter);                              //进行中
        List<NodeNewschedules> allNoFinishedSmallNodes = dao.queryNoFinishedSmallNodesByOperatorPhone(filter);      //未完成
        List<NewProjects> projects = newProjectsService.query();
        Map<String, NewProjects> projectsMap = new HashMap<>();
        for (NewProjects project : projects) {
            if (!projectsMap.containsKey(project.getSysId())) {
                projectsMap.put(project.getSysId(), project);
            }
        }
        //已完成+未完成
        allDoingSmallNodes.addAll(allFinishedSmallNodes);
        allDoingSmallNodes.addAll(allNoFinishedSmallNodes);
        List<String> projectIdList = new ArrayList<>();
        for (NodeNewschedules allSmallNode : allDoingSmallNodes) {
            if (!projectIdList.contains(allSmallNode.getProjectId())) {
                projectIdList.add(allSmallNode.getProjectId());
            }
        }
        for (String projectId : projectIdList) {
            Map<String, Object> resMap = new HashMap<>();
            String projectName = projectsMap.get(projectId).getName();
            List<Map<String, Object>> mapList = new ArrayList<>();
            for (NodeNewschedules finished : allDoingSmallNodes) {
                if (finished.getProjectId().equals(projectId)) {
                    Map<String, Object> map = new HashMap<>();
                    map.put("projectsName", projectName);
                    map.put("sysId", finished.getSysId());
                    map.put("nodeId", finished.getNodeId());
                    map.put("nodeName", finished.getNodeName());
                    map.put("planBeginDate", finished.getPlanBeginDate());
                    map.put("planTime", finished.getPlanTime());
                    map.put("status", finished.getStatus());
                    mapList.add(map);
                }
            }
            if (mapList.size() > 0) {
                resMap.put("projectName",projectsMap.get(projectId).getName());
                resMap.put("list",mapList);
                resList.add(resMap);
            }
        }
        return resList;
    }

    public List<NodeNewschedules> queryList() {
        return dao.queryList();
    }

    public List<NodeNewschedules> queryByFilter(NodeNewschedulesFilter filter) {
        return dao.queryByFilter(filter);
    }

    public int getDataCount() {
        return dao.getDataCount();
    }

    //查询进行中的节点个数
    public BigInteger queryProgressNodesCountByFilter(OnlineFilter filter) {
        return dao.queryProgressNodesCountByFilter(filter);
    }

    //获取各个节点的前置节点
    public Map<String, Object> getEachNodePro(List<NodeNewschedules> nodeList, NewProjects projectList) {
        //各个节点的前置节点
        Map<String, Object> preOfNodeMap = new TreeMap<>();
        for (NodeNewschedules n : nodeList) {
            //筛选确定的节点
            if ("1".equals(n.getState())) {
                //大节点
                if ("1".equals(n.getType())) {
                    if (!preOfNodeMap.containsKey(n.getNodeId())) {
                        preOfNodeMap.put(n.getNodeId(), n.getPreNodeId());
                    }
                } else {
                    //小节点
                    if (!preOfNodeMap.containsKey(n.getNodeId())) {
                        preOfNodeMap.put(n.getNodeId(), preOfNodeMap.get(n.getNodeIds()));
                    }
                }
            }
            if (StringUtils.isNotBlank(n.getFactTime()) && StringUtils.isNotBlank(n.getPlanTime())) {
                if (!"2".equals(n.getStatus())) {
                    n.setIsDelay("-1");     //未完成
                    continue;
                }
                int factTime = Integer.parseInt(n.getFactTime());
                int planTime = Integer.parseInt(n.getPlanTime());
                if (factTime > planTime) {        //实际时间大于计划时间----逾期
                    n.setIsDelay("1");
                } else if (factTime < planTime) {  //实际时间大于计划时间----超前
                    n.setIsDelay("2");
                } else if (factTime == planTime) { //实际时间大于计划时间----正常
                    n.setIsDelay("0");
                }
            }
            n.setCreateDate(projectList.getCreateDate());
        }

        return preOfNodeMap;
    }


    //查看进行中节点情况
    public List<NodeNewschedules> queryNoPageByFilter(NodeNewschedulesFilter filter) {
        return dao.queryNoPageByFilter(filter);
    }

    //查询未确认节点
    public List<NodeNewschedules> queryNoStateNode(String projectId) {
        return dao.queryNoStateNode(projectId);
    }


    public List<NodeNewschedulesModel> addNextNodeDealWith(List<NodeNewschedulesModel> resultNodes) {
        List<NodeNewschedulesModel> bigNodeModel = new ArrayList<>();
        Map<String, String> bigNodeMap = new HashMap<>();
        Map<String, String> preNodeIdMap = new HashMap<>();
        for (NodeNewschedulesModel resultNode : resultNodes) {
            if ("1".equals(resultNode.getType())) {
                bigNodeModel.add(resultNode);
                if (!bigNodeMap.containsKey(resultNode.getNodeId())) {
                    //封装大节点map，下面修改前置节点字段内容要用
                    bigNodeMap.put(resultNode.getNodeId(), resultNode.getNodeId() + "." + resultNode.getNodeName());
                }
                if (!preNodeIdMap.containsKey(resultNode.getNodeId())) {
                    //封装大节点前置节点map，下面修改前置节点字段内容要用
                    preNodeIdMap.put(resultNode.getNodeId(), resultNode.getPreNodeId());
                }
            }
        }
        //排出每个节点的下个节点
        for (NodeNewschedulesModel x : resultNodes) {

            String preNodeIds = "";
            //上个节点查找处理
            //大节点
            if ("1".equals(x.getType())) {
                preNodeIds = preNodeIdMap.get(x.getNodeId());

            }
            //小节点
            if ("2".equals(x.getType())) {
                String nodeId = x.getNodeIds();
                preNodeIds = preNodeIdMap.get(nodeId);
            }
            if (!"#".equals(preNodeIds)) {
                if (!preNodeIds.contains(",")) {
                    if (ObjectUtils.isBlank(bigNodeMap.get(preNodeIds))) {
                        x.setPreNodeId("");
                    } else {
                        x.setPreNodeId(bigNodeMap.get(preNodeIds));
                    }

                } else {
                    String[] arr = preNodeIds.split(",");
                    for (int i = 0; i < arr.length; i++) {
                        if (i == 0) {
                            x.setPreNodeId(bigNodeMap.get(arr[i]));
                        } else {
                            String val = x.getPreNodeId();
                            if (StringUtils.isBlank(val)) {
                                x.setPreNodeId("-");
                            } else {
                                x.setPreNodeId(val + "; " + bigNodeMap.get(arr[i]));
                            }

                        }
                    }

                }
            }


            for (NodeNewschedulesModel y : bigNodeModel) {
                //下个节点查找处理
                String preNodes = y.getPreNodeId();
                String bigNodeId = y.getNodeId();
                String bigNodeName = y.getNodeName();
                if (StringUtils.isBlank(preNodes)) {
                    continue;
                }
                if (preNodes.contains(",")) {
                    String[] preNodesArr = preNodes.split(",");
                    for (String s : preNodesArr) {
                        if ("1".equals(x.getType())) {
                            //大节点
                            if (x.getNodeId().equals(s)) {
                                String val = x.getNextNodes();
                                if (StringUtils.isBlank(val)) {
                                    x.setNextNodes(bigNodeId + "." + bigNodeName);
                                } else {
                                    x.setNextNodes(val + "; " + bigNodeId + "." + bigNodeName);
                                }
                            }
                        }
                        if ("2".equals(x.getType())) {
                            //小节点
                            if (x.getNodeIds().equals(s)) {
                                String val = x.getNextNodes();
                                if (StringUtils.isBlank(val)) {
                                    x.setNextNodes(bigNodeId + "." + bigNodeName);
                                } else {
                                    x.setNextNodes(val + "; " + bigNodeId + "." + bigNodeName);
                                }
                            }
                        }

                    }
                } else {
                    String preNode = preNodes;
                    if ("1".equals(x.getType())) {
                        //大节点
                        if (x.getNodeId().equals(preNode)) {
                            String val = x.getNextNodes();
                            if (StringUtils.isBlank(val)) {
                                x.setNextNodes(y.getNodeId() + " " + y.getNodeName());
                            } else {
                                x.setNextNodes(val + "; " + y.getNodeId() + " " + y.getNodeName());
                            }
                        }
                    }
                    if ("2".equals(x.getType())) {
                        //小节点
                        if (x.getNodeIds().equals(preNode)) {
                            String val = x.getNextNodes();
                            if (StringUtils.isBlank(val)) {
                                x.setNextNodes(y.getNodeId() + " " + y.getNodeName());
                            } else {
                                x.setNextNodes(val + "; " + y.getNodeId() + " " + y.getNodeName());
                            }
                        }
                    }
                }
            }
            if (StringUtils.isBlank(x.getNextNodes())) {
                x.setNextNodes("-");
            }
        }
        return resultNodes;
    }

    public int queryFinishNodesNumInWeek() {
        return dao.queryFinishNodesNumInWeek();
    }
}
